package com.bcu.cn.onlineexamsystem.studentmanage.service.impl;

import com.bcu.cn.onlineexamsystem.studentmanage.entity.ExamDetailForPdf;
import com.bcu.cn.onlineexamsystem.studentmanage.mapper.StudentExamPdfMapper;
import com.bcu.cn.onlineexamsystem.studentmanage.service.StudentExamPdfService;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.BaseFont;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
import java.awt.Color;

@Service
public class StudentExamPdfServiceImpl implements StudentExamPdfService {

    @Autowired
    private StudentExamPdfMapper studentExamPdfMapper;

    @Override
    public void exportExamDetailPdf(Long recordId, String userId, HttpServletResponse response) {
        try {
            ExamDetailForPdf examDetail = studentExamPdfMapper.getExamDetailForPdf(recordId, userId);
            if (examDetail == null) {
                throw new RuntimeException("未找到考试详情");
            }
            examDetail.setQuestions(studentExamPdfMapper.getQuestionDetailsForPdf(recordId));

            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=exam_detail_" + recordId + ".pdf");

            OutputStream out = response.getOutputStream();
            Document document = new Document(PageSize.A4, 36, 36, 36, 36);
            PdfWriter.getInstance(document, out);
            document.open();

            // 中文字体
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font titleFont = new Font(baseFont, 20, Font.BOLD);
            Font headerFont = new Font(baseFont, 12, Font.BOLD);
            Font normalFont = new Font(baseFont, 12, Font.NORMAL);

            // 1. 标题
            Paragraph title = new Paragraph("考试成绩单", titleFont);
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);
            document.add(new Paragraph(" "));

            // 2. 基本信息表格
            PdfPTable infoTable = new PdfPTable(4);
            infoTable.setWidthPercentage(100);
            infoTable.setSpacingBefore(10f);
            infoTable.setSpacingAfter(10f);

            infoTable.addCell(new PdfPCell(new Phrase("考试名称", headerFont)));
            infoTable.addCell(new PdfPCell(new Phrase(safe(examDetail.getExamName()), normalFont)));
            infoTable.addCell(new PdfPCell(new Phrase("课程名称", headerFont)));
            infoTable.addCell(new PdfPCell(new Phrase(safe(examDetail.getCourseName()), normalFont)));

            infoTable.addCell(new PdfPCell(new Phrase("考试类型", headerFont)));
            infoTable.addCell(new PdfPCell(new Phrase(safe(examDetail.getExamType()), normalFont)));
            infoTable.addCell(new PdfPCell(new Phrase("授课教师", headerFont)));
            infoTable.addCell(new PdfPCell(new Phrase(safe(examDetail.getTeacherName()), normalFont)));

            infoTable.addCell(new PdfPCell(new Phrase("所属班级", headerFont)));
            infoTable.addCell(new PdfPCell(new Phrase(safe(examDetail.getClassName()), normalFont)));
            infoTable.addCell(new PdfPCell(new Phrase("总分", headerFont)));
            infoTable.addCell(new PdfPCell(new Phrase(examDetail.getTotalScore() != null ? examDetail.getTotalScore().toString() : "", normalFont)));

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            infoTable.addCell(new PdfPCell(new Phrase("开始时间", headerFont)));
            infoTable.addCell(new PdfPCell(new Phrase(examDetail.getStartTime() != null ? examDetail.getStartTime().format(dtf) : "", normalFont)));
            infoTable.addCell(new PdfPCell(new Phrase("结束时间", headerFont)));
            infoTable.addCell(new PdfPCell(new Phrase(examDetail.getEndTime() != null ? examDetail.getEndTime().format(dtf) : "", normalFont)));

            document.add(infoTable);

            // 3. 题目明细表格
            Paragraph qTitle = new Paragraph("试题明细", headerFont);
            qTitle.setSpacingBefore(10f);
            document.add(qTitle);

            PdfPTable questionTable = new PdfPTable(7);
            questionTable.setWidthPercentage(100);
            questionTable.setSpacingBefore(5f);
            questionTable.setWidths(new float[]{1.2f, 4f, 1f, 2.5f, 2.5f, 1f, 2.5f});

            String[] headers = {"题型", "题目内容", "分值", "参考答案", "我的作答", "得分", "教师评语"};
            for (String h : headers) {
                PdfPCell cell = new PdfPCell(new Phrase(h, headerFont));
                cell.setBackgroundColor(Color.LIGHT_GRAY);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                questionTable.addCell(cell);
            }

            if (examDetail.getQuestions() != null) {
                for (ExamDetailForPdf.QuestionDetailForPdf q : examDetail.getQuestions()) {
                    questionTable.addCell(new PdfPCell(new Phrase(typeName(q.getType()), normalFont)));
                    questionTable.addCell(new PdfPCell(new Phrase(safe(q.getContent()), normalFont)));
                    questionTable.addCell(new PdfPCell(new Phrase(q.getScore() != null ? q.getScore().toString() : "", normalFont)));
                    questionTable.addCell(new PdfPCell(new Phrase(safe(q.getStdAnswer()), normalFont)));
                    questionTable.addCell(new PdfPCell(new Phrase(safe(q.getStudentAnswer()), normalFont)));
                    questionTable.addCell(new PdfPCell(new Phrase(q.getStudentScore() != null ? q.getStudentScore().toString() : "", normalFont)));
                    questionTable.addCell(new PdfPCell(new Phrase(safe(q.getTeacherComment()), normalFont)));
                }
            }
            document.add(questionTable);

            // 4. 结尾
            document.add(new Paragraph(" "));
            DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            document.add(new Paragraph("导出时间：" + LocalDateTime.now().format(dtf2), normalFont));

            document.close();
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException("导出PDF失败", e);
        }
    }

    private String safe(String s) {
        return s == null ? "" : s;
    }

    // 题型中文名
    private String typeName(String type) {
        if (type == null) return "";
        switch (type) {
            case "choice": return "选择题";
            case "multiple": return "多选题";
            case "fill": return "填空题";
            case "essay": return "简答题";
            default: return type;
        }
    }
} 